package com.kystar.ledcontrol.recycleview.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;

import com.google.gson.reflect.TypeToken;
import com.kystar.ledcontrol.recycleview.BaseApp;
import com.kystar.ledcontrol.recycleview.R;
import com.kystar.ledcontrol.recycleview.info.ImageViewInfo;
import com.kystar.ledcontrol.recycleview.util.GsonUtil;
import com.kystar.ledcontrol.recycleview.util.TDevice;

import java.util.ArrayList;
import java.util.List;

public class PerViewActivity extends AppCompatActivity {
    int[] positions;
    List<String> mList;
    ViewPager mViewPager;
    AnimationSet animationSet;
    PreviewPagerAdapter adapter;
    ImageViewInfo mImageViewInfo;
    ImagePickerActivity.MyHandler mHandler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_per_view);
        String s = getIntent().getStringExtra(ImagePickerActivity.PARAM);
        mList = GsonUtil.defaultGson().fromJson(s, new TypeToken<List<String>>() {
        }.getType());
        positions = getIntent().getIntArrayExtra(ImagePickerActivity.INDEX);
        mImageViewInfo = getIntent().getParcelableExtra("imageInfo");
        //        Bitmap bitmap = SaveBitmap.getBitmap();
        //        Drawable drawable = new BitmapDrawable(bitmap);
        //        bitmap.recycle();
        // mViewPager.setBackground(drawable);
        mViewPager = findViewById(R.id.viewPager);
        adapter = new PreviewPagerAdapter(getSupportFragmentManager(), mList, mImageViewInfo);
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(positions[0]);
        // 获得该共享变量实例
        mHandler = BaseApp.getApp().getHandler();
//        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams((int) (2*TDevice.getScreenWidth()/3),
//                (int) TDevice.getScreenHeight()/2);
//        mViewPager.setLayoutParams(layoutParams);
//        mViewPager.setOffscreenPageLimit(2);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        Message message = new Message();
        message.what = endAnim(positions, mImageViewInfo,mViewPager.getCurrentItem(), mViewPager);
        message.arg1 = mViewPager.getCurrentItem();
        mHandler.sendMessage(message);
        intent.putExtra("position", mViewPager.getCurrentItem());
        setResult(RESULT_OK, intent);
        animationSet.start();
        animationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                finish();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private int endAnim(int[] positions, ImageViewInfo imageViewInfo, int overPositon, View view) {
        int isScroll;
        int firstPosition = positions[1];
        int lastPosition = positions[2];
        int viewWidth = imageViewInfo.getImageWidth();
        int viewHeight = imageViewInfo.getImageHeight();
        int x = imageViewInfo.getX();
        int y = imageViewInfo.getY();

        if (overPositon >= firstPosition && overPositon <= lastPosition) {
            isScroll = 0x1;
            x = x+(overPositon%4 - positions[0]%4)*viewWidth;
            y = y+(overPositon/4 - positions[0]/4)*viewHeight;
        } else if (overPositon < firstPosition) {
            int index_x = (overPositon) % 4;
            x = viewWidth * index_x + 6;
            y = 0;
            isScroll = 0x0;
        } else {
            int index_x = (overPositon) % 4;
            x = viewWidth * index_x + 6;
            y = (int) (TDevice.getScreenHeight() - viewHeight);
            isScroll = 0x0;
        }
        ScaleAnimation scaleAnimation = new ScaleAnimation(1, (viewWidth - 4 * 3) / TDevice
                .getScreenWidth(), 1,
                (viewHeight - 4 * 3) / (TDevice.getScreenHeight() - TDevice.getStatusBarHeight()));
        scaleAnimation.setDuration(200);
        TranslateAnimation translateAnimation = new TranslateAnimation(0, x, 0, y);
        translateAnimation.setDuration(200);
        animationSet = new AnimationSet(true);
        animationSet.addAnimation(scaleAnimation);
        animationSet.addAnimation(translateAnimation);//缩放动画需要在移动动画之前加入set集合
        animationSet.setFillAfter(true);
        view.startAnimation(animationSet);
        return isScroll;
    }

    private class PreviewPagerAdapter extends FragmentPagerAdapter {

        private List<String> mItems = new ArrayList<>();
        ImageViewInfo mImageViewInfo;

        public PreviewPagerAdapter(FragmentManager manager, List<String> data, ImageViewInfo
                imageViewInfo) {
            super(manager);
            mItems = data;
            mImageViewInfo = imageViewInfo;
        }

        @Override
        public Fragment getItem(int position) {
            return MyFragment.newInstance(mItems.get(position), mImageViewInfo);
        }

        @Override
        public int getCount() {
            return mItems.size();
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            super.setPrimaryItem(container, position, object);
        }
    }

    @SuppressLint("ValidFragment")
    public static class MyFragment extends Fragment {
        ImageView mImageView;
        String url;
        ImageViewInfo mImageViewInfo;

        public static MyFragment newInstance(String s, ImageViewInfo imageViewInfo) {
            MyFragment fragment = new MyFragment();
            Bundle bundle = new Bundle();
            bundle.putParcelable("imageViewInfo", imageViewInfo);
            bundle.putString("s", s);
            fragment.setArguments(bundle);
            return fragment;
        }

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                                 @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_item_imageview, container, false);
            url = getArguments().getString("s");
            mImageViewInfo = getArguments().getParcelable("imageViewInfo");
            mImageView = view.findViewById(R.id.image);
            return view;
        }

        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            com.kystar.ledcontrol.recycleview.util.GlideApp.with(getActivity()).load(url).into
                    (mImageView);
            initAnim(mImageViewInfo, mImageView);
        }

        private void initAnim(ImageViewInfo imageViewInfo, View view) {
            float widthRadio = imageViewInfo.getImageWidth() / TDevice.getScreenWidth();
            float heightRadio = imageViewInfo.getImageHeight() / TDevice.getScreenHeight();
            ScaleAnimation scaleAnimation = new ScaleAnimation(widthRadio, 1, heightRadio, 1,
                    imageViewInfo.getCenter_x(), imageViewInfo.getCenter_y());
            scaleAnimation.setDuration(200);
            scaleAnimation.setFillAfter(true);
            view.startAnimation(scaleAnimation);
        }

    }
}
